<?php

namespace App\Http\Controllers\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Jobs\OrderJob;
use Carbon\Carbon;

use App\Models\Goods;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\SpecGoodsPrice;
use App\Models\Cart;
use DB;

class OrderController extends Controller
{
    /*
	 * 单个商品生成订单
	 * */
	protected function goodsPay(Request $request){

		$input = $request->only('goods_id','goods_num','spec_key','order_amount',
					'address_username','address_provincename','address_cityname','address_countyname','address_detailinfo','address_mobile','address_zipcode','user_note');
		$uid = $request->uid;
        $validator = \Validator::make($input, [
            'goods_id' => 'required',
            'goods_num' => 'required',
            'order_amount' => 'required',
            'address_username' => 'required',
            'address_detailinfo' => 'required',
            'address_mobile' => 'required',
        ]);
        if ($validator->fails()) {
            $msg = $validator->errors()->first();
			return response()->json([
				'code'	=> '10001',
				'msg'	=> $msg,
				'data'	=> ''
				]);
        }
		$goods = Goods::find($input['goods_id']);
		if(!$goods){
			return response()->json([
				'code'	=> '10001',
				'msg'	=> '商品未找到',
				'data'	=> ''
				]);			
		}
		
		
		if($request->has('goods_num')){
			$goods_num = $request->input('goods_num');
		}else{
			$goods_num = 1;
		}
		$freight = 0;//运费
		$goods_price = $goods->shop_price*$goods_num;//商品总价
		if($request->has('spec_key')){
			$spec_key = $request->input('spec_key');
			$specGoodsPrice = SpecGoodsPrice::where('key',$spec_key)->first();
			if($specGoodsPrice){
				$goods_price = $specGoodsPrice->price;
			}		
		}
		DB::beginTransaction();
		$order = new Order;
		$order->order_sn				= date('Ymd').$uid. str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
		$order->uid						= $uid;
		$order->goods_price				= $goods_price; //商品总价
		$order->total_amount			= $order->goods_price+$freight; //合计
		$order->order_amount			= $order->total_amount; //应付款金额
		$order->address_username		= $input['address_username'];//收货人
		$order->address_provincename	= $input['address_provincename'];//一级地址
		$order->address_cityname		= $input['address_cityname'];//二级地址
		$order->address_countyname		= $input['address_countyname'];//三级地址
		$order->address_detailinfo		= $input['address_detailinfo'];//详细收货地址信息
		$order->address_zipcode			= $input['address_zipcode'];//邮政编码
		$order->address_mobile			= $input['address_mobile'];//手机
		$order->user_note				= $input['user_note'];//用户备注
		$order->shipping_price			= 0;//邮费
		$order->order_status			= 0;//订单状态 0未处理，1已处理，2完成，3取消，4申请退货，5退货中，6已退货
		$order->shipping_status			= 1;//发货状态 1已发货，2未发货,3已送达
		$order->pay_status				= 0;//付款状态
		if(!$order->save()){
			return response()->json([
				'code'	=> '10001',
				'msg'	=> '订单创建失败',
				'data'	=> ''
				]);					
		}
		
		$orderGoods = new OrderGoods;
		$orderGoods->order_id		= $order->order_id;
		$orderGoods->goods_id		= $goods->goods_id;
		$orderGoods->goods_name		= $goods->goods_name;
		$orderGoods->goods_price	= $goods->shop_price;
		$orderGoods->cost_price		= $goods->cost_price;
		$orderGoods->goods_num		= $goods_num;
		$orderGoods->img			= $goods->original_img;
		if(isset($specGoodsPrice)){
			$orderGoods->spec_key		= $specGoodsPrice->key;
			$orderGoods->spec_key_name	= $specGoodsPrice->key_name;
		}
		if(!$orderGoods->save()){
			DB::rollBack();
			return response()->json([
				'code'	=> '10001',
				'msg'	=> '订单创建失败1',
				'data'	=> ''
				]);
		}
		DB::commit();
		//加入队列任务
		$job = (new OrderJob($order->order_id))->delay(Carbon::now()->addMinutes(60));
		dispatch($job);
		return response()->json([
			'code'	=> '00000',
			'msg'	=> '订单创建成功！',
			'data'	=> ''
			]);		

		
		
	}
	
	
	/*
	 * 购物车提交订单
	 * 
	 * */
	protected function cartPay(Request $request){
		$input = $request->only('order_amount','address_username','address_provincename','address_cityname','address_countyname','address_detailinfo','address_mobile','address_zipcode','user_note');
		$uid = $request->uid;
        $validator = \Validator::make($input, [
            'address_username' => 'required',
            'address_detailinfo' => 'required',
            'address_mobile' => 'required'
        ]);
        if ($validator->fails()) {
            $msg = $validator->errors()->first();
			return response()->json([
				'code'	=> '10001',
				'msg'	=> $msg,
				'data'	=> ''
				]);
        }		
		
		$cart = Cart::where('uid',$uid)->where('selected',1)->get();
		if(!$cart){
			return response()->json([
				'code'	=> '10001',
				'msg'	=> '购物车是空的！',
				'data'	=> ''
				]);					
		}
		
		$goods_price = Cart::where('uid',$uid)->where('selected',1)->select(DB::raw('sum(goods_price*goods_num) as goods_price'))->first()['goods_price'];
		$freight = 0;//运费

		DB::beginTransaction();
		$order = new Order;
		$order->order_sn				= date('Ymd').$uid. str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
		$order->uid						= $uid;
		$order->goods_price				= $goods_price; //商品总价
		$order->total_amount			= $order->goods_price+$freight; //合计
		$order->order_amount			= $order->total_amount; //应付款金额
		$order->address_username		= $input['address_username'];//收货人
		$order->address_provincename	= $input['address_provincename'];//一级地址
		$order->address_cityname		= $input['address_cityname'];//二级地址
		$order->address_countyname		= $input['address_countyname'];//三级地址
		$order->address_detailinfo		= $input['address_detailinfo'];//详细收货地址信息
		$order->address_zipcode			= $input['address_zipcode'];//邮政编码
		$order->address_mobile			= $input['address_mobile'];//手机
		$order->user_note				= $input['user_note'];//用户备注
		$order->shipping_price			= 0;//邮费
		$order->order_status			= 0;//订单状态 0未处理，1已处理，2完成，3取消，4申请退货，5退货中，6已退货
		$order->shipping_status			= 1;//0默认，发货状态 1已发货，2未发货,3已送达
		$order->pay_status				= 0;//付款状态
		if(!$order->save()){
			DB::rollBack();
			return response()->json([
				'code'	=> '10001',
				'msg'	=> '订单创建失败',
				'data'	=> ''
				]);					
		}
		

		//生成订单商品数据
		foreach ($cart as $v) {
			$orderGoods = new OrderGoods;
			$orderGoods->order_id		= $order->order_id;
			$orderGoods->goods_id		= $v->goods_id;
			$orderGoods->goods_name		= $v->goods_name;
			$orderGoods->goods_price	= $v->goods_price;
			$orderGoods->cost_price		= $v->cost_price;
			$orderGoods->goods_num		= $v->goods_num;
			$orderGoods->spec_key		= $v->spec_key;
			$orderGoods->spec_key_name	= $v->spec_key_name;
			$orderGoods->img			= $v->img;
			if(!$orderGoods->save()){
				DB::rollBack();
				return response()->json([
					'code'	=> '10001',
					'msg'	=> '订单创建失败1',
					'data'	=> ''
					]);						
				
			}
		}
		DB::commit();
		//删除购车数据
		Cart::whereIn('cart_id',array_column($cart->toarray(), 'cart_id'))->delete();
		//加入队列任务
		$job = (new OrderJob($order->order_id))->delay(Carbon::now()->addMinutes(60));
		dispatch($job);
		return response()->json([
			'code'	=> '00000',
			'msg'	=> '订单创建成功！',
			'data'	=> ''
			]);
	}
	
	/*
	 * 
	 * 订单列表
	 * */
	protected function orderList(Request $request){
		$status = $request->input('status');
		$arr = array(0,1,2,3,4);
		if(!in_array($status,$arr)){
			return response()->json([
				'code'	=> '10001',
				'msg'	=> '参数错误！',
				'data'	=> ''
				]);		
		}
		$uid = $request->uid;
		$orderList = Order::where('uid',$uid)
			->when($status,function($query) use ($status){
				switch ($status) {
					case 1://待付款
						return $query->where('pay_status',0)->where('order_status',0);
						break;
					case 2://待发货
						return $query->where('pay_status',1)->where('shipping_status',1);
						break;		
					case 3://已发货
						return $query->where('pay_status',1)->where('shipping_status',2);
						break;		
					case 4://已完成
						return $query->where('pay_status',1)->where('order_status',2);
						break;																
				}
			})->select('order_id','order_sn','order_status','shipping_status','pay_status','order_amount','created_at')->orderBy('order_id','desc')->paginate(6);
		
		foreach ($orderList as $k=>$v) {
			$orderList[$k]->data = OrderGoods::where('order_id',$v->order_id)->select('rec_id','goods_id','goods_name','goods_price','spec_key_name','spec_key','goods_num','img')->first();	
			$orderList[$k]->goods_count = OrderGoods::where('order_id',$v->order_id)->selectRaw('sum(goods_num) as goods_count')->first()['goods_count'];
		}
		
		return response()->json([
			'code'	=> '00000',
			'msg'	=> 'ok！',
			'data'	=> $orderList
			]);		
		
	}

	/*
	 * 订单详情
	 * 
	 * */
	protected function orderDetails(Request $request){
		$order_id = $request->input('order_id');
		$order = Order::find($order_id);

		$second =  3600-(time()-strtotime($order->created_at));
		if($second <= 0){
			$second = 0;
		}
		$order->goods;
		return response()->json(array(
			'code'	=> '00000',
			'msg'	=> 'ok',
			'data'	=> array(
				'data'	=> $order,
				'second' => $second
				)
			));
		
	}
	
	/*
	 *订单取消
	 * 
	 * */
	protected function orderCancel(Request $request){
		$order_id = $request->input('order_id');
		$order = Order::find($order_id);
		$order->order_status = 3;
		if($order->save()){
			return response()->json(array(
				'code'	=> '00000',
				'msg'	=> '订单已取消！',
				'data'	=> ''
				));			
		}else{
			return response()->json(array(
				'code'	=> '10001',
				'msg'	=> '订单取消失败！',
				'data'	=> ''
				));				
		}
		
	}
	    
}
